import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';
import 'package:ws_group_chat/pages/host/host_wait_page.dart';
import 'package:ws_group_chat/pages/scan_page.dart';
import 'package:ws_group_chat/provider/client_data.dart';
import 'package:ws_group_chat/provider/host_data.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('hi ${context.read<HostData>().userName}'),
            const SizedBox(height: 16),
            // 按钮
            SizedBox(
              width: double.infinity,
              child: OutlinedButton(
                onPressed: () async {
                  await EasyLoading.show(status: '启动服务器...');
                  if (await context.read<HostData>().startServer()) {
                    await EasyLoading.show(status: '获取WS地址...');
                    if (await context.read<HostData>().getWsUrl()) {
                      EasyLoading.dismiss();
                      EasyLoading.showSuccess(
                        '服务器启动成功',
                        duration: const Duration(milliseconds: 300),
                      );
                    } else {
                      EasyLoading.showError('获取WS地址失败');
                      return;
                    }
                  } else {
                    EasyLoading.showError('启动服务器失败');
                    return;
                  }
                  context.read<HostData>().isHost = true;
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const HostWaitPage(),
                    ),
                  );
                },
                child: const Text('创建房间'),
              ),
            ),

            const SizedBox(height: 16),

            SizedBox(
              width: double.infinity,
              child: OutlinedButton(
                onPressed: () {
                  context.read<ClientData>().isHost = false;
                  context.read<HostData>().isHost = false;
                  context.read<ClientData>().userName = context
                      .read<HostData>()
                      .userName;
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const ScanPage()),
                  );
                },
                child: const Text('加入房间'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
